import {HTTP} from "../until/http.js";

class ClassicModel extends HTTP {   //Classic继承了 HTTP的方法
  getLatest(sCallback){  //获取最新一期的期刊
    var that = this;
    this.request({
      url: "/classic/latest",
      success: function (res) {
        wx.setStorageSync(that._getkey(res.index), res);
        sCallback(res);
        that._setLatestIndex(res.index); 
      }
    });   
  }
  getClassic(index,nextorprevious ,sCallback){  //获取期刊 上一期下一期
    //缓存中寻找 or API 写入到缓存中
    //key 确定key
    let key=nextorprevious=="next"?this._getkey(index+1):this._getkey(index-1);
    let classic=wx.getStorageSync(key);
    var that=this;
    if(!classic)
    {
      this.request({
        url: "/classic/" + index + "/" + nextorprevious,
        success: function (res) {
          wx.setStorageSync(that._getkey(res.index),res);
          sCallback(res);
        }
      });
    }else{
      sCallback(classic);
    }
    
  }

  isFirst(index){  //是否是第一个
      return index==1?true:false;
  }
  isLatest(index){  //是否是最新一期
      //因为一刷新页面就会加载最新一期  把最新的编号保存到缓存里 然后比较就可以了
    let lastIndex=this._getLatestIndex();
    return index==lastIndex?true:false;
  }
  _getkey(index){  //设置key的命名
    return "classic-"+index;
  }
  _setLatestIndex(index){  //把最新一期的序号存到缓存里
      wx.setStorageSync("latest", index)
  }
  _getLatestIndex(){  //从缓存中获取最新一期的序号
      let index=wx.getStorageSync("latest");
      return index;
  }
}
export {ClassicModel};